close all;clear;

%---------串口初始化-----------------------------------------------
%设置自己的参数
serialportname  = 'COM8';       % 串口端口名称
serialportboud  = 115200;       % 串口波特率
datasize        = 16;           % 数据处理字长 datasize = 16 ：舍弃低八位  其他：全24位处理 
showlength      = 2000;         % 绘制长度
drawspeed       = 0.001;           % 点绘制速度 单位ms

% 释放串口资源
delete(instrfindall);
s = serialport(serialportname, serialportboud);%创建串口，设置波特率
s.Timeout = 10;
buffer6 = zeros(1, 6);
buffer3 = zeros(1, 3);
drawarray = zeros(1, showlength);
step = 1;
syncflag = 0;

%---------数据读取循环-----------------------------------------------

while true
    % 数据同步
    if syncflag == 0
        if step==1
            a = read(s, step, "uint8");
            buffer6 = [buffer6(2:6) a];
            if buffer6(4) == 128 && buffer6(5) == 0 && buffer6(6) == 128
                step = 6;
                syncflag = 1;
            end
            continue;
        end
    end
    % 数据读取
    buffer6 = read(s, step, "uint8");
    buffer3 = buffer6(1:3);
    disp(buffer3);
    % 数据解析
    if datasize == 16
        data = buffer3(1) * 2^8 + buffer3(2);
        if data > 2^15
            data = data-2^16;
        end
    else
        data = buffer3(1) * 2^16 + buffer3(2)*2^8+ buffer3(3);
        if data > 2^23
            data = data-2^24;
        end
    end
    % 数据存储绘制
    drawarray = [drawarray(2:2000) data];
    plot(drawarray);
    pause(drawspeed/1000);
end
